package com.wan.core.timer;

import com.wan.core.timer.round.IRoundWheel;
import com.wan.core.timer.round.NatureRound;

import java.time.Duration;

/**
 * @author wwh
 * @date 2022/6/27 20:21
 */
public class WTimer {
    /** 自带默认配置时间轮 */
    private static TimerWheel timerWheel;

    /**
     * 获取系统自带默认配置时间轮
     */
    public static TimerWheel get(){
        if(timerWheel != null){
            return timerWheel;
        }
        synchronized (WTimer.class){
            if(timerWheel != null){
                return timerWheel;
            }
            timerWheel = createByEnum("Nature-timer", NatureRound.class,Duration.ofSeconds(1));
        }
        return timerWheel;
    }

    /**
     * 根据指定枚举规则创建时间轮
     * @param ruleClass 枚举类型
     * @param duration 最小单位间隔时间
     */
    public static TimerWheel createByEnum(String name,Class<? extends IRoundWheel> ruleClass, Duration duration){
        //枚举类型创建
        if(ruleClass.isEnum()){
            IRoundWheel[] enumConstants = ruleClass.getEnumConstants();
            if(enumConstants == null || enumConstants.length == 0){
                throw new TimeWheelException("时间轮创建异常,层级规则类型错误,rule->" + ruleClass.getName());
            }
            //枚举中最小叶子节点放在最后
            IRoundWheel roundWheel = enumConstants[enumConstants.length - 1];
            return new TimerWheel(roundWheel,duration,name);
        }
        throw new TimeWheelException("指定类型不是枚举类型,class->" + ruleClass.getName());
    }

    /**
     * 自定义规则创建
     * @param minWheel 自定义规则的最小单位
     * @param duration 最小单位的间隔时间
     */
    public static TimerWheel create(String name,IRoundWheel minWheel,Duration duration){
        return new TimerWheel(minWheel,duration,name);
    }

}
